import email
import imaplib
import time

import PublicDef


def Email_Select(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        domain = str(request.POST.get("domain"))
        if len(name) < 1 and len(domain) < 1:
            return PublicDef.ToJsonRep({"msg": "还未申请临时邮箱哟!", "code": "100", "data": []})
        timestamp = str(request.POST.get("timestamp"))
        if (int(time.time() * 1000) - int(timestamp)) > 10000 or (int(timestamp) - int(time.time() * 1000)) > 10000:
            return PublicDef.ToJsonRep({"msg": "会话超时，请检查系统时间是否与北京时间一致！", "code": "100", "data": []})
        Sign_1 = str(request.POST.get("sign"))
        Sign_2 = PublicDef.Sign(name, timestamp)
        if Sign_1 != Sign_2:
            return PublicDef.ToJsonRep({"msg": "无效会话！"})
        if name == "mimo" or name == "chenpur":
            return PublicDef.ToJsonRep({"msg": "您没有权限查询该账号的相关邮件！", "code": "100", "data": []})
        ret = Select(name, domain)
        return PublicDef.ToJsonRep(ret)
    else:
        return PublicDef.ToJsonRep({"msg": "Only POST", "code": "100", "data": []})


def Select(name, domain):
    datas = []

    try:
        conn = imaplib.IMAP4_SSL(domain[1:len(domain)])
        conn.login(name + domain, "test")
        conn.list()
        conn.select('INBOX')

        result, dataid = conn.search(None, 'ALL')
        mailidlist = dataid[0].split()

        for id in mailidlist:
            try:
                result, data = conn.fetch(id, '(RFC822)')  # 通过邮件id获取邮件
                e = email.message_from_bytes(data[0][1])
                subject = email.header.make_header(email.header.decode_header(e['SUBJECT']))
                mail_from = email.header.make_header(email.header.decode_header(e['From']))
                body = ""
                try:
                    body = str(get_body(e), encoding="utf-8")
                except:
                    body = str(get_body(e), encoding="gb2312")
                tempdata = {
                    "Uid": str(id),
                    "Title": str(subject),
                    "From": str(mail_from),
                    "Value": body
                }
                datas.insert(0, tempdata)
            except:
                continue
        dataa = {
            "code": "0",
            "msg": "Success",
            "data": datas
        }
        return dataa
    except Exception as ex:
        dataa = {
            "code": "100",
            "msg": str(ex),
            "data": datas
        }
        return dataa


def get_body(msg):
    if msg.is_multipart():
        return get_body(msg.get_payload(0))
    else:
        return msg.get_payload(None, decode=True)
